package com.yy.bootdemo.admin.controller;


import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.bootdemo.admin.entity.MyImgEntity;
import com.yy.bootdemo.admin.service.MyImgService;
import com.yy.bootdemo.oss.ConstantPropertiesUtils;
import com.yy.bootdemo.security.utils.PageUtils;
import com.yy.bootdemo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;



/**
 * 图片
 *
 * @author yy
 * @email yangxxil01@sina.com
 * @date 2022-05-05 15:27:17
 */
@RestController
@RequestMapping("img")
public class MyImgController {
    @Autowired
    private MyImgService myImgService;

    /**
     * 列表
     */
    @RequestMapping("/pagelist")
    public R list(@RequestBody PageUtils params){

        // 条件构造器
        QueryWrapper<MyImgEntity> userQuery = Wrappers.query();


        Page<MyImgEntity> page = new Page<>(params.getCurrent(), params.getSize());

        IPage<MyImgEntity> userPage = myImgService.page(page, userQuery);


        return R.ok(userPage);

    }


    /**
     * 信息
     */
    @RequestMapping("/info")
    public R info(@RequestParam Long imgId){
		MyImgEntity myImg = myImgService.getById(imgId);

        return R.ok().put("myImg", myImg);
    }

    /**
     * 保存
     */

    @RequestMapping("/save")
    public R file(@RequestParam Map<String, Object> params, @RequestParam(value = "imgFile", required = false) MultipartFile file) {
      Integer  type =Integer.parseInt(params.get("type") .toString());
        String  description =(String)params.get("description") ;
        //获取上传文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取文件名称
        String fileName = file.getOriginalFilename();
        String url=  uploadFileAvatar(inputStream,fileName);
        MyImgEntity myImg=new MyImgEntity();
        myImg.setType(type);
        myImg.setImgName(fileName);
        myImg.setUrl(url);
        myImg.setDescription(description);
        myImg.setSysState(0);
        myImg.setCreateTime(new Date());
        myImgService.save(myImg);
        return R.ok();
    }

    public String uploadFileAvatar(InputStream inputStream,String fileName) {

        // 工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POIND;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;


            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);



            //1 在文件名称里面添加随机唯一的值
            String uuid = java.util.UUID.randomUUID().toString().replaceAll("-", "");
            // yuy76t5rew01.jpg
            fileName = uuid + fileName;

            //2 把文件按照日期进行分类
            //获取当前日期
            //   2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            //  2019/11/12/ewtqr313401.jpg
            fileName = datePath + "/" + fileName;

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            System.out.println(url);
       return url;
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestParam Map<String, Object> params, @RequestParam(value = "imgFile", required = false) MultipartFile file) {
        Long  imgId =Long.parseLong(params.get("imgId").toString()) ;
        Integer  type =Integer.parseInt(params.get("type") .toString());
        String  description =(String)params.get("description") ;
        //获取上传文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取文件名称
        String fileName = file.getOriginalFilename();
        String url=  uploadFileAvatar(inputStream,fileName);
        MyImgEntity myImg=new MyImgEntity();
        myImg.setImgId(imgId);
        myImg.setType(type);
        myImg.setImgName(fileName);
        myImg.setUrl(url);
        myImg.setDescription(description);
        myImg.setSysState(0);
        myImg.setCreateTime(new Date());


		myImgService.updateById(myImg);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody MyImgEntity myImg){
        Long imgId=myImg.getImgId();
		myImgService.removeById(imgId);

        return R.ok();
    }

}
